package com.temp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.temp.entity.Route;
import com.temp.mapper.RouteMapper;
import com.temp.service.RouteService;
import com.temp.vo.RouteVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Collections.*;

@Service
public class RouteServiceImpl extends ServiceImpl<RouteMapper, Route> implements RouteService {

    @Autowired
    private RouteMapper routeMapper;

    @Override
    public List<RouteVO> findAuthorizedRoutesByUserId(Long userId) {
        // 1. 查询用户有权限的所有启用的路由(包含角色状态检查)，并按sort排序
        List<RouteVO> authorizedRoutes = routeMapper.findAuthorizedRoutesByUserId(userId);

        // 2. 构建树形结构
        return buildConditionRouteTree(authorizedRoutes);
    }

    @Override
    public List<RouteVO> findAllAuthorizedRoutes() {
        List<RouteVO> allAuthorizedRoutes = routeMapper.findAllAuthorizedRoutes();
        return buildRouteTree(allAuthorizedRoutes);
    }

    @Override
    public List<RouteVO> findListRoutes() {
        List<Route> routes = routeMapper.selectList(Wrappers.<Route>lambdaQuery().eq(Route::getStatus, 1));
        List<RouteVO> collect = routes.stream().map(r -> {
            RouteVO routeVO = new RouteVO();
            BeanUtils.copyProperties(r, routeVO);
            routeVO.setChildren(Collections.emptyList());
            return routeVO;
        }).collect(Collectors.toList());
        return buildConditionRouteTree(collect);
    }

    private List<RouteVO> buildRouteTree(List<RouteVO> routes) {
        Map<Long, RouteVO> routeMap = new HashMap<>();
        List<RouteVO> tree = new ArrayList<>();

        // 第一遍：初始化map和children
        for (RouteVO route : routes) {
            route.setChildren(new ArrayList<>());
            routeMap.put(route.getId(), route);
        }

        // 第二遍：构建树结构
        for (RouteVO route : routes) {
            if (route.getParentId() == 0) {
                tree.add(route);
            } else {
                RouteVO parent = routeMap.get(route.getParentId());
                if (parent != null) {
                    parent.getChildren().add(route);
                }
            }
        }

        // 第三遍循环排序并查找子序列第一个路由
        for(RouteVO route : tree) {
            if(route.getChildren().isEmpty()) {
                continue;
            }
            List<Route> children = route.getChildren().stream().sorted(Comparator.comparingInt(Route::getSort)).collect(Collectors.toList());
            route.setChildren(children);
            route.setRedirect(children.get(0).getPath());
        }

        return tree;
    }

    private List<RouteVO> buildConditionRouteTree(List<RouteVO> routes) {
        Map<Long, RouteVO> routeMap = new HashMap<>();
        List<RouteVO> tree = new ArrayList<>();
        Set<Long> toRemove = new HashSet<>();

        for (RouteVO route : routes) {
            route.setChildren(new ArrayList<>());
            routeMap.put(route.getId(), route);
            // 如果当前路由被禁用，标记为需要移除
            if (route.getStatus() == 0) {
                toRemove.add(route.getId());
            }
        }

        // 第二遍：找出所有需要移除的子路由（父路由被禁用的）
        for (RouteVO route : routes) {
            if (route.getParentId() != 0 && toRemove.contains(route.getParentId())) {
                toRemove.add(route.getId());
            }
        }

        // 第三遍：构建树结构，跳过被标记移除的路由
        for (RouteVO route : routes) {
            if (toRemove.contains(route.getId())) {
                continue;
            }

            if (route.getParentId() == 0) {
                tree.add(route);
            } else {
                RouteVO parent = routeMap.get(route.getParentId());
                if (parent != null && !toRemove.contains(parent.getId())) {
                    parent.getChildren().add(route);
                }
            }
        }

        // 第四遍循环排序并查找子序列第一个路由
        for(RouteVO route : tree) {
            if(route.getChildren().isEmpty()) {
               continue;
            }
            List<Route> children = route.getChildren().stream().sorted(Comparator.comparingInt(Route::getSort)).collect(Collectors.toList());
            route.setChildren(children);
            route.setRedirect(children.get(0).getPath());
        }

        return tree;
    }
}
